<?php


namespace app\home\controller;


use app\home\model\ResourceFile;
use app\home\model\WechatDepartment;
use app\home\model\WechatUser;
use app\home\model\WechatUserTag;
use think\Db;

/**
 * Class Resource
 * @package app\home\controller
 * 资源中心
 */
class Resource extends Base
{
    public function _initialize()
    {
        parent::_initialize();
        $this->anonymous();
        $this->jssdk();
        $this->userid = session('userId');
        $user = $this->getTopDepartment($this->userid);
        //权限，1领导，2科室长，3普通员工
         $res = WechatUserTag::where(['userid' => $this->userid])->find();
        if($res) {
            switch ($res['tagid']) {
                case 1: //总经理
                    $permission = 1;
                    break;
                case 2: //副总
                    $permission = 1;
                    break;
                case 3: //科室长
                    $permission = 2;
                    break;
                default: //普通员工
                    $permission = 3;
                    break;
            }
        }else {
            $permission = 3;
        }
        $user['permission'] = $permission;
        $this->user = $user;
        $this->assign('user',json_encode($user));
    }

    /**
     * 主页列表
     */
    public function index () {
        $folder = Db::table('zm_wechat_department')->where(['parentid' => 1])->order('`order` desc')->select();
        $list = [
            'folder' => $folder,
            'file' => []
        ];
        $this->assign('list',json_encode($list));
        return $this->fetch();
    }

    /**
     * 2级列表
     */
    public function index2 () {
        $top_id = input('top_id'); //顶级部门id
        $map = [
            'pid' => 0,
            'top_id' => $top_id,
            'status' => ['egt',0]
        ];
        $folder = Db::table('zm_resource_folder')->where($map)->order('create_time desc')->select();
        $list = [
            'folder' => $folder,
            'file' => []
        ];
        $this->assign('list',json_encode($list));
        return $this->fetch();
    }

    /**
     * 3级列表
     */
    public function index3 () {
        $pid = input('pid');
        $top_id = input('top_id');
        $map = [
            'pid' => $pid,
            'top_id' => $top_id,
            'status' => ['egt',0]
        ];
        $folder = Db::table('zm_resource_folder')->where($map)->order('create_time desc')->select();
        $map_file = [
            'top_id' => $top_id,
            'folder_id' => $pid,
            'status' => ['egt',0]
        ];
        $file = Db::table('zm_resource_file')->where($map_file)->order('create_time desc')->select();
        foreach ($file as $key => $value) {
            $files = \app\admin\model\File::where(['id' => $value['file_id']])->find();
            $file[$key]['path'] = $files ? $files['path'] : '';
            $file[$key]['file_name'] = $files ? $files['name'] : '';
            $file[$key]['file_type'] = $files ? $files['ext'] : '';
            $file[$key]['file_size'] = $files ? $this->sizecount($files['size']) : '';
        }
        $list = [
            'folder' => $folder,
            'file' => $file
        ];
        $this->assign('list',json_encode($list));
        return $this->fetch();
    }

    /**
     * 文件列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function filelist() {
        $id = input('id');
        $top_id = input('top_id');
        $map = [
            'folder_id' => $id,
            'top_id' => $top_id,
            'status' => ['egt',0]
        ];
        $file = Db::table('zm_resource_file')->where($map)->order('create_time desc')->select();
        foreach ($file as $key => $value) {
            $files = \app\admin\model\File::where(['id' => $value['file_id']])->find();
            $file[$key]['path'] = $files ? $files['path'] : '';
            $file[$key]['file_name'] = $files ? $files['name'] : '';
            $file[$key]['file_type'] = $files ? $files['ext'] : '';
            $file[$key]['file_size'] = $files ? $this->sizecount($files['size']) : '';
        }
        $list = [
            'folder' => [],
            'file' => $file
        ];
        $this->assign('list',json_encode($list));

        return $this->fetch();
    }

    /**
     * 搜索
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function search() {
        $user = $this->user;
        $name = input('name');
        $map = [
            'top_id' => $user['topid'],
            'name' => ['like', "%".$name."%"],
            'status' => ['egt',0],
        ];
        if($user['departmentid'] == 10) {
            unset($map['top_id']);
        }
        $list =  Db::table('zm_resource_file')->where($map)->order('create_time desc')->select();
        if($list) {
            foreach ($list as $key => $value) {
                $files = \app\admin\model\File::where(['id' => $value['file_id']])->find();
                $list[$key]['path'] = $files ? $files['path'] : '';
                $list[$key]['file_name'] = $files ? $files['name'] : '';
                $list[$key]['file_type'] = $files ? $files['ext'] : '';
                $list[$key]['file_size'] = $files ? $this->sizecount($files['size']) : '';
            }
            return $this->success("查询成功","",$list);
        }else {
            return $this->error("查询失败");
        }
    }

    /**
     * 资源中心文件上传
     * file_id,
     * folder_id
     */
    public function fileupload () {
        $Model = new ResourceFile();
        $user = $this->user;
        if(IS_POST) {
            $data = input('post.');
            $data['top_id'] = $user['topid'];
            $data['userid'] = $user['userid'];
            $data['username'] = $user['username'];
            $exists = $Model->where('name', $data['name'])->find();
            if($exists) {
                return $this->error("存在相同文件名称，请重新命名!");
            }else {
                $res = $Model->create($data);
                if($res) {
                    return $this->success("创建成功","",$res);
                }else {
                    return $this->error("创建失败");
                }
            }
        }else {
            $map = [
                'status' => ['egt',0],
                'userid' => $user['userid']
            ];
            $list = $Model->where($map)->order('update_time desc,create_time desc')->limit(0,8)->select();
            foreach ($list as $key => $value) {
                $list[$key]['update_time'] = $value['update_time'] ? $value['update_time'] : $value['create_time'];
                $file = \app\admin\model\File::where(['id' => $value['file_id']])->find();
                $list[$key]['file_name'] = $file ? $file['name'] : '';
                $list[$key]['file_type'] = $file ? $file['ext'] : '';
                $list[$key]['file_size'] = $file ? $this->sizecount($file['size']) : '';
            }
            $this->assign('list',json_encode($list));
            return $this->fetch();
        }
    }

    /**
     * 加载更多
     */
    public function morelist() {
        $Model = new ResourceFile();
        $user = $this->user;
        $length = input('length',0);
        $map = [
            'status' => ['egt',0],
            'userid' => $user['userid']
        ];
        $list = $Model->where($map)->order('update_time desc,create_time desc')->limit($length,8)->select();
        if($list) {
            return $this->success("加载成功","",$list);
        }else {
            return $this->error("加载失败");
        }
    }

    /**
     * 获取当前用户所属科室
     */
    private function getTopDepartment($userid) {
        $userModel = new WechatUser();
        $departmentModel = new WechatDepartment();
        $user = $userModel->where(['userid' => $userid])->find();
        $department = $departmentModel->where(['id' => $user['department']])->find();
        $depart = $department['id'];
        //查找顶级部门id
        if($department['parentid'] == 1) {
            $top_depart = $department['id'];
        }else {
            $department2 = $departmentModel->where(['id' => $department['parentid']])->find();
            if($department2['parentid'] == 1) {
                $top_depart = $department2['id'];
            }else {
                $department3 = $departmentModel->where(['id' => $department2['parentid']])->find();
                if($department3['parentid'] == 1) {
                    $top_depart = $department3['id'];
                }else {
                    return $this->error("查找不到该用户所在科室！");
                }
            }
        }
        $return = [
            'userid' => $userid,
            'username' => $user['name'],
            'topid' => $top_depart,
            'departmentid' => $depart,
        ];
        return $return;
    }

    /**
     * 转化文件大小
     */
    private function sizecount($filesize) {
        if($filesize >= 1073741824) {
            $filesize = round($filesize / 1073741824 * 100) / 100 . ' gb';
        } elseif($filesize >= 1048576) {
            $filesize = round($filesize / 1048576 * 100) / 100 . ' mb';
        } elseif($filesize >= 1024) {
            $filesize = round($filesize / 1024 * 100) / 100 . ' kb';
        } else {
            $filesize = $filesize . ' bytes';
        }
        return $filesize;
    }
}
